import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View
from lapi_app.models.environment_model.environment import Environment
from lapi_app.view.user_view.token_check import access_token


class Env_view(View):

    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        if not access_token(data["user_id"]):
            return JsonResponse({
                "code": 1001,
                "message": "登录失效，请重新登录"
            })
        if data["env_name"] == "":
            envs = Environment.objects.all().order_by("-id")
        else:
            envs = Environment.objects.filter(e_name__contains=data["env_name"])
        size_page = data["size_page"]
        current_pages = data["current_page"]
        case_total = len(envs)
        env_list = []
        for env in envs:
            env_dict = {
                "environment_id": env.id,
                "environment_name": env.e_name,
                "environment_address": env.e_address,
                "environment_e_describe": env.e_describe,
                "update_time": datetime.strftime(env.update_time, "%Y-%m-%d %H:%M:%S"),
                "create_time": datetime.strftime(env.create_time, "%Y-%m-%d %H:%M:%S"),
                "username": env.e_user.username
            }
            env_list.append(env_dict)
        p = Paginator(env_list, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "message": "获取环境列表成功",
            "content": current_page,
            "case_total": case_total,
            "size_page": size_page,
            "current_page": current_pages
        })
